import { Algorithm } from "../types"

// 数据模型定义
interface MPLPNode {
  id: any
  type: string
  attributes: Record<string, any>
}

interface MPLPEdge {
  source: any
  target: any
  type?: string
  weight?: number
  attributes: Record<string, any>
}

interface MPLPGraph {
  nodes: MPLPNode[]
  edges: MPLPEdge[]
}

// 定义时序图数据结构
interface TemporalGraph {
  nodes: MPLPNode[]
  edges: MPLPEdge[]
  timestamp: string
}

// THGAD算法输入参数
interface THGADInputParams {
  graph_sequence: TemporalGraph[]
  window_size: number
  contamination: number
}

// 异常结果接口
interface AnomalyResult {
  node_id: any
  anomaly_score: number
  node_type: string
}

// 异常解释接口
interface AnomalyExplanation {
  node_type: string
  anomaly_score: number
  feature_anomalies?: Record<string, any>
}

interface AlgorithmRequest {
  task_id: string
  task_callback_url?: string
  input_params: {
    thgad_params: THGADInputParams
  }
}

// 元路径链接预测算法实现
export const TemporalHeterogeneousGraphAnomalyDetection: Algorithm = {
  name: "时序异构图异常检测算法(THGAD)",
  description: "基于时间序列的异构图异常节点检测算法，用于检测图中随时间变化的异常节点",
  configOptions: [
    {
      id: "window_size",
      label: "时间窗口大小",
      type: "number",
      defaultValue: 5,
      placeholder: "5"
    },
    {
      id: "contamination",
      label: "污染率",
      type: "number",
      defaultValue: 0.1,
      placeholder: "0.1"
    },
    {
      id: "inputData",
      label: "输入数据",
      type: "textarea",
      placeholder: `请输入JSON格式的时序图数据序列，例如：
[
  {
    "nodes": [
      {
        "id": "n1",
        "type": "用户",
        "attributes": {"age": 25, "activity": 0.8}
      },
      {
        "id": "n2",
        "type": "商品",
        "attributes": {"price": 199, "category": "电子产品"}
      }
    ],
    "edges": [
      {
        "source": "n1",
        "target": "n2",
        "type": "购买",
        "weight": 1.0,
        "attributes": {"timestamp": "2023-01-01"}
      }
    ],
    "timestamp": "2023-01-01"
  },
  {
    "nodes": [...],
    "edges": [...],
    "timestamp": "2023-01-02"
  }
]`
    }
  ],
  execute: async (config) => {
    try {
      // 生成唯一的任务ID
      const taskId = `thgad_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
      
      // 解析输入数据
      let graphSequence: TemporalGraph[]
      try {
        graphSequence = JSON.parse(config.inputData)
      } catch (e) {
        throw new Error("输入数据必须是有效的JSON格式")
      }

      // 验证输入数据结构
      if (!Array.isArray(graphSequence) || graphSequence.length === 0) {
        throw new Error("输入数据必须是时序图数据数组")
      }

      // 准备请求数据
      const requestData: AlgorithmRequest = {
        task_id: taskId,
        task_callback_url: "",
        input_params: {
          thgad_params: {
            graph_sequence: graphSequence,
            window_size: Number(config.window_size) || 5,
            contamination: Number(config.contamination) || 0.1
          }
        }
      }

      // 创建任务
      const createResponse = await fetch("http://172.16.4.151:1122/api/thgad/create", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(requestData)
      })

      if (!createResponse.ok) {
        const errorData = await createResponse.json()
        if (createResponse.status === 422) {
          const validationErrors = errorData.detail || []
          const errorMessages = validationErrors.map((err: any) => 
            `${err.loc?.join('.')}: ${err.msg}`
          ).join('\n')
          throw new Error(`数据验证错误:\n${errorMessages}`)
        }
        throw new Error(errorData.detail || "创建任务失败")
      }

      // 执行任务
      const executeResponse = await fetch(`http://172.16.4.151:1122/api/thgad/execute/${taskId}`, {
        method: "POST"
      })

      if (!executeResponse.ok) {
        const errorData = await executeResponse.json()
        throw new Error(errorData.detail || "执行任务失败")
      }

      // 轮询获取结果
      let result
      let attempts = 0
      const maxAttempts = 60

      while (attempts < maxAttempts) {
        const getResultResponse = await fetch(`http://172.16.4.151:1122/api/thgad/result/${taskId}`)
        
        if (!getResultResponse.ok) {
          const errorData = await getResultResponse.json()
          throw new Error(errorData.detail || "获取结果失败")
        }

        result = await getResultResponse.json()
        
        // 添加日志以便调试
        console.log(`第${attempts + 1}次尝试获取结果:`, result.task_status)

        if (result.task_status === "COMPLETED") {
          break
        } else if (result.task_status === "FAILED") {
          throw new Error(result.error_message || "任务执行失败")
        }

        await new Promise(resolve => setTimeout(resolve, 1000))
        attempts++
      }

      if (attempts >= maxAttempts) {
        throw new Error("任务执行超时")
      }

      // 处理结果
      if (!result.output_params?.thgad_results) {
        throw new Error("结果结构不正确，缺少thgad_results")
      }

      const outputParams = result.output_params.thgad_results
      
      // 生成结果摘要
      const resultText = `时序异构图异常节点检测完成：
检测到的异常节点数量: ${outputParams.anomalies.length}
算法: ${outputParams.algorithm || "THGAD"}`

      // 生成异常节点表格
      const anomalyNodesText = outputParams.anomalies.length > 0 
        ? `异常节点列表:
${outputParams.anomalies.map((node: AnomalyResult, index: number) => 
  `${index+1}. 节点ID: ${node.node_id} (类型: ${node.node_type}, 异常分数: ${(node.anomaly_score * 100).toFixed(2)}%)`
).join('\n')}`
        : "未检测到异常节点"

      return {
        result: `${resultText}\n\n${anomalyNodesText}`,
        steps: [],
        executionTime: 0,
        details: {
          anomalies: outputParams.anomalies,
          parameters: outputParams.parameters,
          algorithm: outputParams.algorithm
        }
      }
    } catch (e: any) {
      console.error("THGAD算法执行出错:", e)
      throw e
    }
  }
} 